package com.libra.assemble.web.controller.authority;

import com.libra.assemble.entity.authority.Sidebar;
import com.libra.assemble.service.authority.SidebarService;
import com.libra.assemble.web.form.ActionMessageForm;
import com.libra.assemble.xutil.Constants;
import com.libra.assemble.xutil.web.Servlets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.ServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 菜单信息管理的业务代理.
 *
 * @author Libra
 */
@Controller
@RequestMapping(value = "/sidebar")
public class SidebarController {

    private static Logger logger = LoggerFactory.getLogger(SidebarController.class);

    /**
     * 菜单管理的业务逻辑
     */
    @Autowired
    private SidebarService sidebarService;

    /**
     * 菜单列表.
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public String list(@RequestParam(value = "nodeid",required=false) Long nodeid,Model model) {
        model.addAttribute("nodeid",nodeid);
        logger.info("菜单信息.....");
        return "authority/sidebar-list";
    }



    /**
     * 菜单信息列表，返回JSON.(分页、查询)
     * @param pageNumber
     * @param pageSize
     * @param name
     * @return
     */
    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public Page<Sidebar> list(@RequestParam(value = "page", defaultValue = "1") int pageNumber,
                                 @RequestParam(value = "page.size", defaultValue = Constants.PAGE_SIZE_10) int pageSize,
                                 @RequestParam(value = "nodeid",required=false) Long nodeid,
                                 @RequestParam(value = "name",required=false) String name){

        return sidebarService.getSidebar(nodeid, name, pageNumber, pageSize);
    }


    /**
     * 进入菜单创建页面.
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String create(Model model) {
        model.addAttribute("sidebar", new Sidebar());
        model.addAttribute("topSidebars", sidebarService.getTopSidebar());
        model.addAttribute("action", "create");
        return "authority/sidebar-form";
    }

    /**
     * 创建菜单.
     *
     * @param newSidebar
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "create", method = RequestMethod.POST)
    public String create(@Valid Sidebar newSidebar, RedirectAttributes redirectAttributes) {
        newSidebar.setCreateTime(new Date());
        sidebarService.saveSidebar(newSidebar);
        redirectAttributes.addFlashAttribute("message", new ActionMessageForm("success", "很好", "菜单［" + newSidebar.getName() + "］添加成功。"));
        return "redirect:/sidebar/";
    }


    /**
     * 进入菜单更新页面.
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "update/{id}", method = RequestMethod.GET)
    public String update(@PathVariable("id") Long id, Model model) {
        model.addAttribute("sidebar", sidebarService.getSidebar(id));
        model.addAttribute("topSidebars", sidebarService.getTopSidebar());
        model.addAttribute("action", "update");
        return "authority/sidebar-form";
    }

    /**
     * 提交更新的菜单信息.
     *
     * @param sidebar
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public String update(@Valid @ModelAttribute("sidebar") Sidebar sidebar, RedirectAttributes redirectAttributes) {
        sidebarService.saveSidebar(sidebar);
        redirectAttributes.addFlashAttribute("message", new ActionMessageForm("success", "很好！", "菜单［" + sidebar.getName() + "］已成功更新。"));
        return "redirect:/sidebar";
    }

    /**
     * 删除菜单记录.
     *
     * @param id
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "delete/{id}")
    public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
        sidebarService.deleteSidebar(id);
        redirectAttributes.addFlashAttribute("message", new ActionMessageForm("warning", "注意：", "菜单已被成功删除！"));
        return "redirect:/sidebar";
    }

    /**
     * 所有RequestMapping方法调用前的Model准备方法, 实现预处理部分绑定的效果,先根据form的id从数据库查出Sidebar对象,再把Form提交的内容绑定到该对象上。
     * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
     */
    @ModelAttribute
    public void getSidebar(@RequestParam(value = "id", defaultValue = "-1") Long id, @RequestParam(value = "preSidebar.id", defaultValue = "-1") Long preSidebarId, Model model) {
        if (id != -1) {
            Sidebar sidebar = sidebarService.getSidebar(id);
            if (preSidebarId > 0) {
                logger.info("id>0");
                sidebar.setPreSidebar(sidebarService.getSidebar(preSidebarId));
            }
            model.addAttribute("sidebar", sidebar);
        }
    }


    /**
     * 取得所有菜单信息，组合树JSON格式返回.
     * @return
     */
    @RequestMapping(value="tree")
    @ResponseBody
    public String tree(){

        StringBuffer sb=new StringBuffer();
        sb.append("[");
        for(Sidebar sidebar : sidebarService.getTopSidebar()) {
            childTree(sb, sidebar);
        }
        sb.append("]");
        return sb.toString().replace(",]", "]");
    }

    /**
     * 取得所有菜单信息，组合树JSON格式返回（异步）.
     * @return
     */
    @RequestMapping(value="asyn_tree")
    @ResponseBody
    public String asynTree(){
        StringBuffer sb=new StringBuffer();
        sb.append("[");
        for(Sidebar sidebar : sidebarService.getTopSidebar()) {
            asynChildTree(sb,sidebar);
        }
        sb.append("]");
        return sb.toString().replace(",]", "]");
    }

    /**
     * 取得子菜单数据.
     * @param nodeid
     * @return
     */
    @RequestMapping(value="asyn_children")
    @ResponseBody
    public String asynchildren(@RequestParam(value = "nodeid") Long nodeid){
        List<Sidebar> sdebars = sidebarService.getSidebar(nodeid).getSidebars();

        StringBuffer sb=new StringBuffer();
        sb.append("[");
        if(!sdebars.isEmpty()){
            for(Sidebar sdebar : sdebars){
                sb.append("{ \"id\":"+sdebar.getId()+",\"name\":\""+sdebar.getName()+"\"");
                if(!sdebar.getSidebars().isEmpty()){
                    sb.append(",\"hasChild\":\"true\"");
                }
                sb.append("},");
            }
        }
        sb.append("]");

        return sb.toString().replace(",]", "]");
    }

    /**
     * 递归获取菜单的直属下级(组合JSON格式的菜单树).
     * @param sb
     * @param sidebar
     * @return
     */
    private void childTree(StringBuffer sb,Sidebar sidebar ){
        sb.append("{ \"id\":"+sidebar.getId()+",\"name\":\""+sidebar.getName()+"\"");
        List<Sidebar> list = sidebar.getSidebars();
        if(!list.isEmpty()){
            sb.append(",\"children\":[");
            for(Sidebar child : list){
                childTree(sb,child);
            }
            sb.append("]");
        }
        sb.append("},");
    }

    /**
     * 递归获取菜单的直属下级(组合JSON格式的菜单树)（异步）.
     * @param sb
     * @param sidebar
     * @return
     */
    private void asynChildTree(StringBuffer sb,Sidebar sidebar ){
        sb.append("{ \"id\":"+sidebar.getId()+",\"name\":\""+sidebar.getName()+"\"");
        if(!sidebar.getSidebars().isEmpty()){
            sb.append(",\"hasChild\":\"true\"");
        }
        List<Sidebar> list = sidebar.getSidebars();
        if(!list.isEmpty()){
            sb.append(",\"children\":[");
            for(Sidebar child : list){
                asynChildTree(sb,child);
            }
            sb.append("]");
        }
        sb.append("},");
    }


}
